/** 
 * @Title:  WelcomeController.java 
 * @author:  xuron
 * @data:  2015年11月23日 上午10:51:24 <创建时间>
 * 
 * @history：<以下是历史记录>
 *
 * @modifier: <修改人>
 * @modify date: 2015年11月23日 上午10:51:24 <修改时间>
 * @log: <修改内容>
 *
 * @modifier: <修改人>
 * @modify date: 2015年11月23日 上午10:51:24 <修改时间>
 * @log: <修改内容>
 */
package com.woyou.controller;

import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.jing.biandang.R;
import com.woyou.Constants;
import com.woyou.WoYouApplication;
import com.woyou.activity.HomeActivity;
import com.woyou.activity.LoginActivity;
import com.woyou.activity.WelcomeActivity;
import com.woyou.bean.DeliveryTime;
import com.woyou.bean.UserInfo;
import com.woyou.bean.WYList;
import com.woyou.bean.rpc.Result;
import com.woyou.bean.rpc.ServerTimeRes;
import com.woyou.bean.rpc.UpdateVersionReq;
import com.woyou.bean.rpc.UpdateVersionRes;
import com.woyou.bean.rpc.UserLoginReq;
import com.woyou.bean.rpc.UserLoginRes;
import com.woyou.component.SuperUI;
import com.woyou.model.rpc.ShopModel;
import com.woyou.model.rpc.UserModel;
import com.woyou.utils.DownloadeManager;
import com.woyou.utils.LightManager;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.MainBoardUtil;
import com.woyou.utils.NavigationbarUtils;
import com.woyou.utils.PrintNumUtils;
import com.woyou.utils.TypeJudgeTools;
import com.woyou.utils.Utils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import retrofit.RetrofitError;

/**
 * 提取welcome页面的逻辑
 * 
 * @author xuron
 * @versionCode 1 <每次修改提交前+1>
 */
public class WelcomeController extends SuperController {
	private WelcomeActivity welcomeActivity;
	/**
	 * 更新信息
	 */
	private Result<UpdateVersionRes> updateVersionResult;
	/**
	 * 更新超时倒计时
	 */
	private int updateTimeOut = 0;
	/**
	 * 是否取消更新超时倒计时
	 */
	private boolean isUpdateTimeout = true;
	/**
	 * 是否等待新特性的显示完成
	 */
	private boolean isWaitfor = true;
	/**
	 * 是否正在尝试登陆
	 */
	private boolean isTryToLogin = true;
	/**
	 * 引导动画Timer
	 */
	private Timer guideTimer;
	private TimerTask guideTimerTask;
	/**
	 * 引导页倒计时
	 */
	private int nowTime = 10;

	private String bdjCode;
	private String code;
	private String pwd;
	private String shopUserCode;
	// 刚开机初始化，deviceCode和versionCode可能获取不到
	private String deviceCode;
	private String versionCode;
	private int loginType;
	long startTime = System.currentTimeMillis();
	long endTime = System.currentTimeMillis();
	/**
	 * 登陆请求参数
	 */
	private UserLoginReq userLoginReq;
	/**
	 * 登陆返回参数
	 */
	private UserLoginRes userLoginRes;
	/**
	 * 结果
	 */
	private Result<UserLoginRes> result;

	/**
	 * @param mContext
	 */
	public WelcomeController(Context mContext) {
		super(mContext);
		this.mContext=mContext;
		welcomeActivity=(WelcomeActivity)mContext;
	}

	/**
	 * 根据UserInfo跳转到下一页面
	 * @param userInfo
	 * @param load_tv
	 * @param introduct_guide
	 * @param introduct_hand
	 * @param introduct_time
	 * @param introduct_time_tv
	 */
	public void judge2Page(final UserInfo userInfo,final TextView load_tv,final RelativeLayout welcome_panel,final RelativeLayout introduct_guide,final ImageView introduct_hand,final RelativeLayout introduct_time,final TextView introduct_time_tv){
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				runOnUI(new Runnable() {
					public void run() {
						// 判断当前版本和缓存本地记录的版本是否一致，如果不一致则显示介绍页面，并自动登录
						if (userInfo != null&&userInfo.getVersion().equals("" + WoYouApplication.VersionCode)) {
							autoLogin(welcomeActivity,userInfo,load_tv);
						} else {
							isWaitfor = false;
							welcome_panel.setVisibility(View.GONE);
							guideAnim(welcomeActivity,userInfo,load_tv,introduct_guide,introduct_hand,introduct_time,introduct_time_tv);
						}
					}
				});
			}
		}, 1000);
	}

	/**
	 * 自动登录
	 */
	public void autoLogin(final WelcomeActivity welcomeActivity,final UserInfo userInfo,final TextView load_tv) {
		isWaitfor = true;
		// 读取SharedPreferences中的用户登录信息
		if (userInfo != null && !TextUtils.isEmpty(userInfo.getPwd())) {
			// 再次登录
			bdjCode = userInfo.getbId();
			code = userInfo.getCode();
			pwd = userInfo.getPwd();
			shopUserCode = userInfo.getuCode();
			deviceCode = userInfo.getDeviceId();
			versionCode = userInfo.getVersion();
			loginType = 1;
		} else {
			// 跳转到登陆页面
			Intent intent = new Intent(mContext, LoginActivity.class);
			mActivity.startActivity(intent);
			mActivity.finish();
			return;
		}
		executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					if (!pwd.equals("") && !shopUserCode.equals("")&& !versionCode.equals("")) {

						int i = 0;
						int j = 0;
						// 尝试登陆30s
						while (isTryToLogin) {
							endTime = System.currentTimeMillis();
							//同步服务器时间
							// 做一个计时器同步服务器时间
							if(!syncServerTime(load_tv)){
								if ((endTime - startTime) >= 30000) {
									Intent intent = new Intent(mContext,LoginActivity.class);
									mActivity.startActivity(intent);
									mActivity.finish();
									return;
								}
								autoLogin(welcomeActivity,userInfo,load_tv);
								return;
							}
							
							if (!TypeJudgeTools.isNull(deviceCode)&& !TypeJudgeTools.isNull(versionCode)) {
								userLoginReq = new UserLoginReq();
								userLoginReq.setbId(bdjCode);
								userLoginReq.setuCode(shopUserCode);
								userLoginReq.setCode(code);
								userLoginReq.setPwd(pwd);
								userLoginReq.setLoginType(loginType);
								userLoginReq.setDeviceId(deviceCode);
								userLoginReq.setVersion(versionCode);

								// 自动登录
								changeTextInfo(load_tv, "正在验证用户登录信息" + 50 + "%");
								result = UserModel.getInstance(mContext).v2_3userLogin(userLoginReq);
								if (result != null && result.code == 1) {
									userLoginRes = result.getData();
								} else if(result != null && result.code ==-3){
									runOnUI(new Runnable() {
										public void run() {
											SuperUI.openToast(mContext,result.msg);
										}
									});
									clearUserInfo(mContext);
									return;
								}
							}
							// 延迟3000毫秒重试
							Thread.sleep(3000);
							if (userLoginRes != null&& !TypeJudgeTools.isNull(userLoginRes.getsName())) {
								break;
							} else if ((endTime - startTime) >= 30000) {
								break;
							}
						}

						if (result != null && result.code == 1) {
							if (userLoginRes != null&& !TypeJudgeTools.isNull(userLoginRes.getsName())) {
								// 存储用户登录信息
								aCache.put("loginUserInfo", userLoginRes);
								UserInfo userInfo = new UserInfo();
								userInfo.setbId(userLoginReq.getbId());
								userInfo.setsId(userLoginRes.getsId());
								userInfo.setuCode(userLoginReq.getuCode());
								userInfo.setsName(userLoginRes.getsName());
								userInfo.setCode(userLoginReq.getCode());
								userInfo.setPwd(userLoginReq.getPwd());
								userInfo.setLoginType(userLoginReq.getLoginType());
								userInfo.setDeviceId(userLoginReq.getDeviceId());
								userInfo.setVersion(WoYouApplication.VersionCode+"");
								userInfo.setServerIP(userLoginRes.getServerIP());
								userInfo.setServerPort(userLoginRes.getServerPort());
								// 存储外卖时间段
								List<DeliveryTime> deliveryList = userLoginRes.getDeliveryTimeList();
								if (deliveryList != null) {
									WYList<DeliveryTime> deliveryWyList = new WYList<DeliveryTime>();
									deliveryWyList.addAll(deliveryList);
									aCache.put("delivertime", deliveryWyList);
								}
								// 将用户信息存到sp中
								LoginUtils.saveUserInfo(userInfo,mContext);
								// 将用户信息存到TF卡中
								Utils.writeUserInfo2TF(userInfo);

								// 默认设置营业中
								Constants.shopStatus = "S";
								// 设置店铺id
								Constants.shopCode = userLoginRes.getsId();
								// 设置店铺名
								Constants.shopName = userLoginRes.getsName();
								Constants.HEART_BEAT_SERVER = userLoginRes.getServerIP();
								if (!TypeJudgeTools.isNull(userLoginRes.getServerPort())) {
									Constants.HEART_BEAT_SERVER_PORT = Integer.valueOf(userLoginRes.getServerPort());
								}
								// 检测更新
								checkUpdate(welcomeActivity,load_tv);
							} else {
								SuperUI.openToast(mContext,result.msg);
								while (true) {
									if (isWaitfor) {
										Intent intent = new Intent(mContext,LoginActivity.class);
										mActivity.startActivity(intent);
										mActivity.finish();
										break;
									}
								}
							}
						} else {
							while (true) {
								if (isWaitfor) {
									Intent intent = new Intent(mContext,LoginActivity.class);
									mActivity.startActivity(intent);
									mActivity.finish();
									break;
								}
							}
						}
					} else {
						while (true) {
							if (isWaitfor) {
								Intent intent = new Intent(mContext,LoginActivity.class);
								mActivity.startActivity(intent);
								mActivity.finish();
								break;
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					try{
						// 延迟3000毫秒重试
						Thread.sleep(3000);
					}catch(Exception exception){
					}
					endTime = System.currentTimeMillis();
					if ((endTime - startTime) >= 30000) {
						while (true) {
							if (isWaitfor) {
								Intent intent = new Intent(mContext,LoginActivity.class);
								mActivity.startActivity(intent);
								mActivity.finish();
								break;
							}
						}
					} else {
						Utils.setMobileDataEnabled(mContext, true);
						autoLogin(welcomeActivity,userInfo,load_tv);
					}
				}
			}
		});
	}

	/**
	 * 引导动画
	 */
	public void guideAnim(final WelcomeActivity welcomeActivity,final UserInfo userInfo,final TextView load_tv,final RelativeLayout introduct_guide,ImageView introduct_hand,final RelativeLayout introduct_time,final TextView time_tv) {
		introduct_guide.setVisibility(View.VISIBLE);
		TranslateAnimation translateAnimation = new TranslateAnimation(600,-300, 0, 0);
		introduct_hand.setAnimation(translateAnimation);
		translateAnimation.setDuration(2000);
		translateAnimation.setRepeatCount(1);
		translateAnimation.setFillBefore(true);
		translateAnimation.start();
		// 隐藏动画
		guideTimer = new Timer();
		guideTimerTask = new TimerTask() {
			@Override
			public void run() {
				runOnUI(new Runnable() {
					public void run() {
						introduct_guide.setVisibility(View.GONE);
						introduct_time.setVisibility(View.VISIBLE);
						if(nowTime>=0){
							time_tv.setText((nowTime--)+ "s后自动进入...");
						}
						if (nowTime == 0) {
							// 跳转到登陆页面
							autoLogin(welcomeActivity,userInfo,load_tv);
							// 关闭引导动画
							closeGuideTimer();
						}
					}
				});
			}
		};
		guideTimer.schedule(guideTimerTask, 4000, 1000);
	}

	/**
	 * 关闭引导Timer
	 */
	public void closeGuideTimer(){
		if (guideTimer != null) {
			guideTimer.cancel();
			guideTimer = null;
		}
		if (guideTimerTask != null) {
			guideTimerTask.cancel();
			guideTimerTask = null;
		}
	}

	/**
	 * 销毁Destroy
	 */
	public void onDestroy(){
		isTryToLogin = false;
		isWaitfor = false;
		closeGuideTimer();
	}

	/**
	 * 提示更新的dialog
	 * 
	 * @param isForce
	 *            是否强制更新
	 * @param context
	 * @param updateInfo3
	 */
	public void openUpdateDialog(final WelcomeActivity welcomeActivity,boolean isForce, final Context context, final UpdateVersionRes updateVersionRes) {

		final Dialog dialog = new Dialog(context, R.style.defaultDialogStyle);
		View view = LayoutInflater.from(context).inflate(R.layout.layout_checkupdate, null);
		TextView checkupdate_info = (TextView) view.findViewById(R.id.layout_checkupdate_info);
		RelativeLayout checkupdate_cancel = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_cancel);
		final TextView layout_checkupdate_cancel_tv = (TextView) view.findViewById(R.id.layout_checkupdate_cancel_tv);
		RelativeLayout checkupdate_down = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_down);
		// 根据标志位判断是否显示取消更新按钮
		if (isForce) {
			checkupdate_cancel.setVisibility(View.GONE);
		} else {
			checkupdate_cancel.setVisibility(View.VISIBLE);
		}
		dialog.setContentView(view);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		checkupdate_info.setText(updateVersionRes.getInfo().replace("<LF>", "\n"));
		checkupdate_cancel.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				isUpdateTimeout = false;
				dialog.dismiss();
				jump2Home();
			}
		});
		checkupdate_down.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				isUpdateTimeout = false;
				dialog.dismiss();
				new DownloadeManager(mActivity, "" + updateVersionRes.getUpdateUrl())
						.showDownloadDialog(welcomeActivity, true);
			}
		});
		// 等待更新超时
		executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					updateTimeOut = 60;
					while (isUpdateTimeout) {
						runOnUI(new Runnable() {
							public void run() {
								if (updateTimeOut == 1) {
									isUpdateTimeout = false;
									dialog.dismiss();
									jump2Home();
								}
								layout_checkupdate_cancel_tv.setText("以后再说(" + (updateTimeOut--) + ")");
							}
						});
						// 延迟1s
						Thread.sleep(1000);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 检测软件更新
	 */
	public void checkUpdate(final WelcomeActivity welcomeActivity,final TextView load_tv) {
		executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					changeTextInfo(load_tv, "正在检测应用更新信息" + 100 + "%");
					UpdateVersionReq updateVersionReq = new UpdateVersionReq();
					updateVersionReq.setAppName("BD_VERSION2");
					updateVersionReq.setBoardType(MainBoardUtil.getModel());
					updateVersionReq.setPwd(LoginUtils.getUserInfo(mContext).getPwd());
					updateVersionReq.setsId(LoginUtils.getUserInfo(mContext).getsId());
					updateVersionReq.setVersion(LoginUtils.getUserInfo(mContext).getVersion());
					updateVersionResult = UserModel.getInstance(mContext).updateVersion(updateVersionReq);
					runOnUI(new Runnable() {
						@Override
						public void run() {
							if (updateVersionResult != null && updateVersionResult.code == 1&& updateVersionResult.getData() != null) {
								UpdateVersionRes updateVersionRes = updateVersionResult.getData();
								if (updateVersionRes != null && updateVersionRes.getIsUpdate() == 1) {
									if (updateVersionRes.getType() == 1) {
										// 强制更新
										openUpdateDialog(welcomeActivity,true, mContext, updateVersionRes);
									} else {
										// 选择更新
										openUpdateDialog(welcomeActivity,false, mContext, updateVersionRes);
									}
								} else {
									jump2Home();
								}
							} else if (updateVersionResult != null && updateVersionResult.code == -3) {
								runOnUI(new Runnable() {
									@Override
									public void run() {
										SuperUI.openToast(mContext, "您的账号已在其他地方登陆，请您重新登录！");
										Intent intent = new Intent(mContext, LoginActivity.class);
										mActivity.startActivity(intent);
										mActivity.finish();
									}
								});
							} else {
								jump2Home();
							}
						}
					});
				} catch (RetrofitError error) {
					switch (error.getKind()) {
					case CONVERSION:
						runOnUI(new Runnable() {
							public void run() {
								SuperUI.openToast(mContext, "服务器又任性了！");
							}
						});
						break;
					case HTTP:
						runOnUI(new Runnable() {
							public void run() {
								SuperUI.openToast(mContext, "服务器又任性了！");
							}
						});
						break;
					case NETWORK:
						runOnUI(new Runnable() {
							public void run() {
								SuperUI.openToast(mContext, "请检查网络连接！");
							}
						});
						break;
					case UNEXPECTED:
						runOnUI(new Runnable() {
							public void run() {
								SuperUI.openToast(mContext, "请检查网络连接！");
							}
						});
						break;

					default:
						break;
					}
					Intent intent = new Intent(mContext, LoginActivity.class);
					mActivity.startActivity(intent);
					mActivity.finish();
				}
			}
		});
	}

	/**
	 * 根据传入参数设置焦点
	 * 
	 * @param index
	 */
	public void setItemFocus(int index, ImageView iv1, ImageView iv2, ImageView iv3) {
		iv1.setImageResource(R.raw.icon_introduct_unfocus);
		iv2.setImageResource(R.raw.icon_introduct_unfocus);
		iv3.setImageResource(R.raw.icon_introduct_unfocus);
		switch (index) {
		case 0:
			iv1.setImageResource(R.raw.icon_introduct_focus);
			break;
		case 1:
			iv2.setImageResource(R.raw.icon_introduct_focus);
			break;
		case 2:
			iv3.setImageResource(R.raw.icon_introduct_focus);
			break;
		}
	}

	/**
	 * 同步服务器时间 成功返回true ,失败返回false
	 * 
	 * @return
	 */
	public boolean syncServerTime(TextView load_tv) {
		try {
			changeTextInfo(load_tv, "正在同步服务器时间" + 25 + "%");
			// 尝试3次获取服务器时间
			for (int i = 0; i < 3; i++) {
				Result<ServerTimeRes> result = ShopModel.getInstance(mContext).queryServerTime();
				if (result != null && result.getCode() == 1 && result.getData() != null) {
					// 储存服务器时间到aCache中
					aCache.put("ServerTime", result.getData().getsTime() * 1000 + "");
					return true;
				}
			}
		} catch (Exception e) {
		}
		return false;
	}

	/**
	 * 自动登录成功跳转到home页面
	 */
	public void jump2Home() {
		Intent intent = new Intent(mContext, HomeActivity.class);
		mActivity.startActivity(intent);
		mActivity.finish();
	}

	/**
	 * 检查本地缓存的老数据
	 */
	public UserInfo updateUserInfo() {
		UserInfo userInfo;
		UserInfo user = LoginUtils.getUserInfo(mContext);
		if (user != null && user.getPwd().equals("")) {
			userInfo = new UserInfo();
			String bdjCode = LoginUtils.getBdjCode(mContext);
			String code = LoginUtils.getPwd(mContext);
			String shopUserCode = LoginUtils.getShopUserCode(mContext);
			if (!bdjCode.equals("") && !code.equals("") && !shopUserCode.equals("")) {
				userInfo.setbId(bdjCode);
				userInfo.setCode(code);
				userInfo.setuCode(shopUserCode);
				userInfo.setDeviceId(user.getDeviceId());
				userInfo.setPwd(producePwd(userInfo));
				userInfo.setServerIP(user.getServerIP());
				userInfo.setServerPort(user.getServerPort());
				userInfo.setsId(user.getsId());
				userInfo.setsName(user.getsName());
				userInfo.setVersion(user.getVersion());
				// 写入sp
				LoginUtils.saveUserInfo(userInfo, mContext);
				// 写入TF卡
				Utils.writeUserInfo2TF(userInfo);
			}
		} else {
			userInfo = Utils.readUserInfo4TF();
			if (userInfo != null && userInfo.getbId().equals("")) {
				// 写入sp
				LoginUtils.saveUserInfo(userInfo, mContext);
				// 写入TF卡
				Utils.writeUserInfo2TF(userInfo);
			}
		}
		return userInfo;
	}

	/**
	 * 设置密码
	 * 
	 * @param userInfo
	 * @return
	 */
	public String producePwd(UserInfo userInfo) {
		if (userInfo != null && !TextUtils.isEmpty(userInfo.getPwd())) {
			return userInfo.getPwd();
		}
		Random random = new Random();
		int num = 0;
		while (true) {
			num = (int) (random.nextDouble() * (1000000 - 100000) + 100000);
			if (!(num + "").contains("4"))
				break;
		}
		return String.valueOf(num);
	}

	/**
	 * 修改加载进度信息
	 */
	public void changeTextInfo(final TextView load_tv, final String info) {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				load_tv.setText(info);
			}
		});
	}

	/**
	 * 清除本地用户信息并跳转到登陆页面
	 */
	public void clearUserInfo(Context mContext) {
		// 清除登录信息
		Utils.removeUserInfo2TF();
		LoginUtils.removeUserInfo(mContext);
		LoginUtils.removeUser(mContext);
		// 清除打印订单数
		PrintNumUtils.clearPrintNum(mContext);
		// 跳转到登陆页面
		Intent intent = new Intent(mContext, LoginActivity.class);
		mActivity.startActivity(intent);
		mActivity.finish();
	}

	/**
	 * 重置机器状态
	 */
	public void resetMacStatus() {
		NavigationbarUtils.getInstance(mContext).hide();
		// 关闭闪烁灯
		LightManager.turnOnRedLight(false);
		LightManager.turnOnBlueLight(false);
		LightManager.turnOnRedBlueLight(false);
	}
}
